import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse} from "axios";

export default class HttpRequest {
    public instance: AxiosInstance;
    private baseUrl: string;

    constructor(baseUrl: string) {
        this.baseUrl = baseUrl;
        this.instance = axios.create({
            baseURL: baseUrl,
            withCredentials: true,
        });
        HttpRequest.interceptors(this.instance)
    }

    private static interceptors(instance: AxiosInstance) {
        instance.interceptors.request.use(
            (config) => {
                return config;
            },
            (e) => {
                return Promise.reject(e);
            }
        );

        instance.interceptors.response.use(
            (res: AxiosResponse) => {
                const {code, data} = res.data;
                if (code === 200) {
                    return data;
                }
                // 状态码不是200的情况处理
                return Promise.reject(res);
            },
            (error: any) => {
                return Promise.reject(error);
            }
        );
    }

    /**
     * 网络请求
     * @param options
     */
    public request<T = any>(options: AxiosRequestConfig): Promise<T> {
        return this.instance.request(options);
    }
}